package com.vhall.component.service.common;

import com.vhall.component.framework.oss.enums.GuoXinOssUrlEnum;
import com.vhall.component.plugin.common.config.OssSettings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.MessageFormat;

/**
 * @author shimingming
 * @since 2023/9/21 14:12
 */
@Slf4j
@Service
public class BaseCommonService {

    @Value("${spring.profiles.active:''}")
    private String active;

    @Autowired
    private OssSettings settings;

    /**
     * 国信使用sandstone 云，这里需要把地址转换成对应请求路径的
     */
    public Object convertUrl(Object obj, String... columnNmae) {
        // 统一使用国信外网域名
        return obj;
//        if (StringUtils.isNotBlank(active) && "prod".equals(active) && "sandStone".equals(settings.getType())) {
//
//            // 获取对象的所有属性
//            Field[] fields = obj.getClass().getDeclaredFields();
//
//            // 遍历属性
//            for (Field field : fields) {
//                try {
//                    for (String column : columnNmae) {
//                        if (column.equals(field.getName())) {
//                            // 转换操作
//                            dealConvertUrl(obj, field);
//                        }
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    log.error(MessageFormat.format("转换url 异常：【{0}--【{1}】】", e.getMessage(), field.getName()));
//                }
//            }
//        }
//        return obj;
    }

    private void dealConvertUrl(Object obj, Field field) throws IllegalAccessException {
        // 设置属性可访问
        field.setAccessible(true);
        if (field.get(obj) != null) {
            String originUrl = field.get(obj).toString();
            if (StringUtils.isNotBlank(originUrl)) {
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = servletRequestAttributes.getRequest();
                StringBuffer requestUrl = request.getRequestURL();

                String needReplaceUrl = GuoXinOssUrlEnum.getOssDomain(requestUrl.toString());
                if (StringUtils.isNotBlank(needReplaceUrl)) {

                    String newUrl = originUrl.replaceAll(GuoXinOssUrlEnum.CLIENT.getOssDomain(), needReplaceUrl);
                    field.set(obj, newUrl);
                }
            }
        }
    }
}
